import { ICompatibleAdapter, ProtocolType } from './core/interfaces';
import { SystemScanner, AdapterGenerator, DefaultRuleEngine } from './dynamic';
import { DatabaseMiddleware, DatabaseAdapter, DatabaseDialect, RoutingStrategy } from '../database/Router';
import { PlatformFactory } from './platform/PlatformFactory';

type SecurityContext = {
    allowSystemAccess: boolean;
    maxPrivilegeLevel: number;
};

export class AdapterRegistry {
    private adapters: ICompatibleAdapter[] = [];
    private securityContext: SecurityContext = {
        allowSystemAccess: false,
        maxPrivilegeLevel: 0
    };
    private databaseMiddleware?: DatabaseMiddleware;

    setSecurityContext(context: Partial<SecurityContext>) {
        this.securityContext = { ...this.securityContext, ...context };
    }

    register(adapter: ICompatibleAdapter): void {
        this.adapters.push(adapter);
    }

    getBestAdapter(protocol?: ProtocolType): ICompatibleAdapter | null {
        // 首先筛选出支持的适配器
        const supportedAdapters = this.adapters.filter(adapter => 
            adapter.isSupported() && 
            (!protocol || adapter.supportsProtocol(protocol))
        );

        if (supportedAdapters.length === 0) {
            return null;
        }

        // 简单示例：选择第一个支持的适配器
        // 实际应用中可以实现更复杂的优先级逻辑
        return supportedAdapters[0];
    }

    async resolveHostname(hostname: string): Promise<string> {
        // 优先使用专门的DNS适配器
        const dnsAdapter = this.getBestAdapter(ProtocolType.DNS);
        if (dnsAdapter && dnsAdapter.resolve) {
            return dnsAdapter.resolve(hostname);
        }

        // 回退到其他支持DNS的适配器
        for (const adapter of this.adapters) {
            if (adapter.supportsProtocol(ProtocolType.DNS) && adapter.resolve) {
                return adapter.resolve(hostname);
            }
        }

        throw new Error('No DNS resolver adapter available');
    }

    async executeNativeCommand(
        protocol: ProtocolType,
        command: string,
        options?: { elevated?: boolean }
    ): Promise<string> {
        // 安全检查
        if (!this.securityContext.allowSystemAccess) {
            throw new Error('System access not allowed in current security context');
        }

        if (options?.elevated && this.securityContext.maxPrivilegeLevel < 1) {
            throw new Error('Insufficient privilege level for elevated operation');
        }

        const adapter = this.getBestAdapter(protocol);
        if (!adapter) {
            throw new Error(`No adapter found for protocol: ${protocol}`);
        }

        return adapter.execute(command);
    }

    async convertProtocol(
        fromProtocol: ProtocolType,
        toProtocol: ProtocolType,
        data: any
    ): Promise<any> {
        // 简单的协议转换逻辑
        // 实际应用中可以实现更复杂的转换规则
        const sourceAdapter = this.getBestAdapter(fromProtocol);
        const targetAdapter = this.getBestAdapter(toProtocol);

        if (!sourceAdapter || !targetAdapter) {
            throw new Error('Protocol conversion not supported');
        }

        const intermediate = await sourceAdapter.execute(data);
        return targetAdapter.execute(intermediate);
    }

    async discoverAndRegisterDynamicAdapters(): Promise<void> {
        if (!this.securityContext.allowSystemAccess) {
            throw new Error('System scanning requires allowSystemAccess=true');
        }

        const scanner = new SystemScanner();
        const interfaces = await scanner.scan();
        const ruleEngine = DefaultRuleEngine.createDefault();
        const generator = new AdapterGenerator(ruleEngine);

        for (const intf of interfaces) {
            try {
                const adapterCode = generator.generateAdapter(intf);
                const adapter = await this.compileAndLoadAdapter(adapterCode);
                this.register(adapter);
                console.log(`Registered dynamic adapter for ${intf.name}`);
            } catch (error) {
                console.error(`Failed to generate adapter for ${intf.name}:`, error);
            }
        }
    }

    private async compileAndLoadAdapter(code: string): Promise<ICompatibleAdapter> {
        // 实际实现需要调用TypeScript编译器或使用eval（仅限开发环境）
        // 这里简化处理，实际项目应考虑安全性和性能
        const tempFile = `./temp/DynamicAdapter_${Date.now()}.js`;
        await fs.promises.writeFile(tempFile, code);
        
        // 动态加载生成的适配器
        const module = await import(tempFile);
        return new module[Object.keys(module)[0]]();
    }

    getAdapters(): ICompatibleAdapter[] {
        return [...this.adapters];
    }

    initDatabaseMiddleware(dialect: DatabaseDialect, strategy: RoutingStrategy) {
        const dbAdapters = this.adapters.filter(a => 
            a.supportsProtocol(ProtocolType.DATABASE)
        ) as DatabaseAdapter[];
        
        this.databaseMiddleware = new DatabaseMiddleware(
            dbAdapters,
            dialect,
            strategy
        );
    }

    async executeSQL(sql: string): Promise<any> {
        if (!this.databaseMiddleware) {
            throw new Error('Database middleware not initialized');
        }
        return this.databaseMiddleware.execute(sql);
    }

    // 平台操作方法
    async readFile(path: string, encoding = 'utf-8'): Promise<string> {
        if (!this.securityContext.allowSystemAccess) {
            throw new Error('File system access not allowed in current security context');
        }
        return PlatformFactory.getPlatform().readFile(path, encoding);
    }

    async writeFile(path: string, content: string): Promise<void> {
        if (!this.securityContext.allowSystemAccess) {
            throw new Error('File system access not allowed in current security context');
        }
        return PlatformFactory.getPlatform().writeFile(path, content);
    }

    async execCommand(command: string): Promise<{ stdout: string, stderr: string }> {
        if (!this.securityContext.allowSystemAccess) {
            throw new Error('Command execution not allowed in current security context');
        }
        if (command.trim().startsWith('sudo') && this.securityContext.maxPrivilegeLevel < 1) {
            throw new Error('Insufficient privilege level for sudo command');
        }
        return PlatformFactory.getPlatform().execCommand(command);
    }

    getCurrentPlatformType(): string {
        return PlatformFactory.getPlatform().getPlatformType();
    }

    // 网络适配器管理
    getNetworkAdapter(protocol: string): NetworkAdapter {
        if (!this.securityContext.allowNetworkAccess) {
            throw new Error('Network access not allowed in current security context');
        }
        return PlatformFactory.getAdapter(protocol);
    }

    // 表格API管理
    createTableAPI(type: 'excel' | 'google-sheets', config: any): TableAPI {
        if (!this.securityContext.allowDataAccess) {
            throw new Error('Data access not allowed in current security context');
        }

        switch (type) {
            case 'excel':
                return new ExcelAdapter(config.filePath);
            case 'google-sheets':
                return new GoogleSheetsAdapter(config.spreadsheetId);
            default:
                throw new Error(`Unsupported table API type: ${type}`);
        }
    }

    // 驱动检测
    detectAvailableDrivers(): string[] {
        return PlatformFactory.detectAvailableDrivers();
    }
}